package com.moli.iov.manager;


import com.moli.iov.cache.RedisUtil;
import com.moli.iov.manager.activemq.ActiveMQProducer;
import com.moli.iov.manager.model.po.AuthoritySysUser;
import com.moli.iov.manager.service.IAuthoritySysUserService;
import com.moli.iov.manager.service.IDictDataService;
import com.moli.iov.util.SpringContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * <p>
 * 启动类
 * </p>
 *
 * @Auther: liws
 * @Date: 2018/11/29 18:40
 */
public class StartManager {

    private static final Logger logger = LoggerFactory.getLogger(StartManager.class);

    private static final String SERVICE_NAME = "iov-service-manager";


    public static void main(String[] args) {
        logger.info("*********************{}正在启动*********************", SERVICE_NAME);
        //加载spring配置文件
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring/spring-base.xml");
        ctx.start();
        initDict();
        expireMq();
        logger.info("*********************{}启动成功*********************", SERVICE_NAME);

        synchronized (StartManager.class) {
            while (true)
                try {
                    StartManager.class.wait();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
        }
    }

    private static void initDict() {
        IDictDataService iDictDataService = SpringContextUtils.getBean("dictDataService");
        iDictDataService.cacheAllDict();
        logger.info("*********************{}启动成功*********************", "缓存字典信息成功！");
    }


    /**
     * 查询未来即将过期用户集合，放到MQ的延时消息中，时间到置为停用状态
     */
    private static void expireMq() {
        IAuthoritySysUserService sysUserService = SpringContextUtils.getBean("iAuthoritySysUserService");
        if (sysUserService == null) {
            return;
        }
        List<AuthoritySysUser> expiringUsers = sysUserService.getExpiringUsers();
        if (expiringUsers == null || expiringUsers.size() <= 0) {
            return;
        }
        ActiveMQProducer activeMQProducer = SpringContextUtils.getBean("activeMQProducer");
        for (AuthoritySysUser expiringUser : expiringUsers) {
            //置为停用状态
            expiringUser.setStatus(1);
            Long diffTime;
            long time = expiringUser.getDisableTime().getTime();
            long l = System.currentTimeMillis();
            if (time > l) {
                diffTime = time - l;
                activeMQProducer.send(expiringUser, diffTime);
            }
        }
    }
}
